/*
 * Copyright (C) 2004, Velocityme Partnership
 * SessionTree.java
 *
 * Created on 11 July 2004, 03:26
 */

package com.velocityme.www.dto;


import java.util.*;
import com.velocityme.valueobjects.*;
import com.velocityme.www.dto.*;

import org.apache.commons.beanutils.*;
/**
 *
 * @author  bradloff
 */
public class SessionTree {
    List tree = new ArrayList();
    NodeValue root = null;
    /** Creates a new instance of SessionTree */
    public SessionTree(NodeValue p_root) {
        root = p_root;
    }
    
    public List getTree(){
        return tree;
    }
    
    public void addCollection(Integer p_parentId, Collection p_col){
        try{
        if(p_col!=null){
            int parentIndex = getIndexOfNode(p_parentId.intValue());
            Iterator i = p_col.iterator();
            List branch = new ArrayList();
            while(i.hasNext()){
                WebNodeValue webNode = new WebNodeValue();
                NodeValue node = (NodeValue)i.next();
                BeanUtils.copyProperties(webNode,  node);
                webNode.setParentId(p_parentId.intValue());
                branch.add(webNode);
            }
            tree.addAll(parentIndex + 1, branch);
        }
        }catch(Exception error){
            error.printStackTrace();
        }
    }
    
    private int getIndexOfNode(int p_nodeId){
        Iterator i = tree.iterator();
        int index = -1;
        int current = 0;
        while(i.hasNext()){
            WebNodeValue node = (WebNodeValue)i.next();
            if(p_nodeId == node.getNodeId().intValue()){
                break;
            }
            current++;
        }
        if(current != tree.size())index = current;
        return index;
    }
        
    public NodeValue getRoot(){
        return root;
    }
    
}
